package cn.wolfcode.web.controller;

import cn.wolfcode.anno.RequiredPermission;
import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.query.JSONResult;
import cn.wolfcode.query.QueryObject;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.awt.*;
import java.util.List;

@Controller // 标识一下 可以被扫描 创建对象 加入spring容器
@RequestMapping("/role") // 访问路径的映射地址   作用 ： 可以通过浏览器 进行访问的地址
public class RoleController {
    @Autowired// 自动装配  DepartmentService
    private IRoleService roleService;
    @Autowired// 自动装配  DepartmentService
    private IPermissionService permissionService;

    @RequestMapping("/list")
    @RequiredPermission({"角色列表权限","RoleController.list"})
    public String list(Model model, @ModelAttribute("qo") QueryObject qo) {  // 返回值是String   返回值的内容 一般是一个地址
        PageInfo pageInfo = roleService.findAll(qo);
        // 把数据共享给页面
        model.addAttribute("pageInfo", pageInfo);
        return "/role/list";
    }
    @RequestMapping("/delete")
    @ResponseBody
    @RequiredPermission({"角色删除权限","RoleController.delete"})

    public JSONResult delete(Long id) {
        try {
            roleService.deleteById(id);
            return new JSONResult();
        } catch (Exception e){
            e.printStackTrace();
            return new JSONResult().mark("删除失败，请稍后重试");
        }

    }
    @RequestMapping("/input")
    @RequiredPermission({"角色添加权限","RoleController.input"})
    public String input(Long id,Model model) {
        if (id != null) {
            //根据id获取部门信息
            Role role=roleService.findById(id);
            //把数据共享到页面
            model.addAttribute("entity",role);


        }
        List<Permission> permissions = permissionService.listAll();
        model.addAttribute("permissions",permissions);

        return "/role/input";
    }
    @RequestMapping("/saveOrUpdate")
    @RequiredPermission({"角色更新权限","RoleController.saveOrUpdate"})
    public String saveOrUpdate(Role role,Long[] ids) {
        roleService.saveOrUpdate(role,ids);
        return "redirect:/role/list";
    }//redirect重定向
}
